/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package models.dados;

import config.HibernateConfig;
import config.LogErro;
import javax.swing.JOptionPane;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Wenderson
 */
public class HibernateUtil {
    
    private static SessionFactory sessionFactory = getSessionFactory();
            //new Configuration().configure().buildSessionFactory();
    
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    
    private static SessionFactory getSessionFactory() {
        HibernateConfig hc = new HibernateConfig();
        
        if (hc.getProperties() == null) {
            JOptionPane.showMessageDialog(null, "Conexão do FrameWork inválida.\n\nVerifique o arquivo \"configFrameWork.xml\"");
            return null;
        }
        
        try {
            Configuration c = new Configuration();
            c.setProperties(hc.getProperties());
            
            return c.configure().buildSessionFactory();            
        } catch (Exception e) {
            LogErro.gravaErro(e);
            e.printStackTrace();
        }
        return null;
    }
    
    public static void restartSessionFactory() {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
        
        sessionFactory = getSessionFactory();
    }
    
    public static Session getSession() {
        Session session = threadLocal.get();
        
        if (session == null || !session.isOpen()) {
            restartSessionFactory();
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        
        return session;
    }
    
    public static void beginTransaction() {
        try {
            getSession().beginTransaction();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }
    
    public static void commitTransaction() {
        getSession().getTransaction().commit();
    }
    
    public static void rollBackTransaction() {
        getSession().getTransaction().rollback();
    }
    
    public static void closeSession() {
        getSession().close();
    }
}
